/**
 * 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出与target最接近的三个值，并返回他们的和。
 * <p>
 *  
 * <p>
 * 示例：
 * <p>
 * 输入：nums = [-1,2,1,-4], target = 1
 * 输出：2
 * 解释：与 target 最接近的和是 -1 + 2 + 1 ，其和是2 。
 */
class Solution {

    public static void main(String[] args) {
        System.out.println(threeSumClosest(new int[]{-1, 2, 1, -4}, 1));
    }

    /**
     * 记录位置
     */
    public static int[] res;
    public static int one;
    public static int two;
    public static int three;

    public static int threeSumClosest(int[] nums, int target) {
        res = new int[]{0, 1, 2};
        int tmp;
        // 处理前三个
        one = Math.abs(nums[0] - target);
        two = Math.abs(nums[1] - target);
        three = Math.abs(nums[2] - target);
        if (one < two) {
            // 如果2小于3
            tmp = res[0];
            res[0] = res[1];
            res[1] = tmp;
            tmp = one;
            one = two;
            two = tmp;
        }
        for (int i = 3; i < nums.length; i++) {
            tmp = Math.abs(nums[i] - target);
            if (tmp < three) {
                three = tmp;
                res[2] = i;
                sort();
            }
        }
        int sum = 0;
        for (int i = 0; i < res.length; i++) {
            sum += nums[res[i]];
        }
        return sum;
    }

    private static void sort() {
        if (one < three) {
            // 如果1小于3
            int tmp = res[0];
            res[0] = res[2];
            res[2] = res[1];
            res[1] = tmp;
            tmp = one;
            one = three;
            three = two;
            two = tmp;
        } else if (two < three) {
            // 如果2小于3
            int tmp = res[1];
            res[1] = res[2];
            res[2] = tmp;
            tmp = two;
            two = three;
            three = tmp;
        }
    }

}